<?php

require_once("model/Datos.php");

class Etiqueta
{
	var $tabla = "etiquetas";

	var $value = array(
						'id'		=>'0',
						'nombre'	=>'nombre',
						'peso'		=>'0'
					);
						
	
	function index($where=null, $datos = null){
		
		$query = "SELECT ";
		
		$query2 = " FROM " . $this->tabla;
		
		foreach($this->value as $k=>$v){
		
			$query .=  $k . ",";
									
		}
				
		$query = substr($query, 0, strlen($query)-1);
		
		if(!empty($where)){
			
			$cond = "";
			
			foreach($where as $k=>$v){
			
				$cond .= $k  . " LIKE '" . $v . "' AND";
						
			}
			
			$query2 .= " WHERE " . substr($cond, 0, strlen($cond)-3);
		}
		
		$query .= $query2;
//echo $query;		
		$data = mysql_db_query($datos->database, $query);
		
		$etiquetas = array();
		
		if(!empty($data))
		
		while($i = mysql_fetch_array($data)) {
		
			$img = array(
						'id'		=> $i['id'],
						'nombre'	=> $i['nombre'],
						'peso'		=> $i['peso']
					);
			$etiquetas[] = $img;

		}
				
		
		
		return $etiquetas;		
	}


	function save($etiquetas){
		
		$status = true;
		
		$datos2 = new Datos();
		
		$datos2->conectar();

		$query = "INSERT INTO ". $this->tabla ."(nombre,peso) ";
		
		$query2 = " VALUES('";
				
		$e = explode(',', $etiquetas);
		
		foreach($e as $etiqueta)
		{
			$peso = 1;
			
			$existingLabel = $this->index(array('nombre' => $etiqueta), $datos2);
			
			if(!empty($existingLabel))
			{
				$existingLabel[0]['peso'] += 1;
				
				$this->edit($existingLabel[0], $datos2);
				
			}
			else
			{
				
				$q = $query . $query2 . $etiqueta . "'," . $peso . ")";
//echo $q;
				$status = mysql_query($q);
			}
		
		}			
		
		$datos2->desconectar();
		
		return $status;		
	}
	
	function edit($e, $datos2){
		
		$status = true;
		
		//$datos2 = new Datos();
		
		//$datos2->conectar();

		$query = "UPDATE ". $this->tabla ." SET peso=" . $e['peso'];
		
		$query2 = " WHERE id=" . $e['id'];
		
		$q = $query . $query2;
//echo $q;
		$status = mysql_query($q);		
		
		//$datos2->desconectar();
		
		return $status;		
	}

	function delete($e){
		
		$where = array('id'=>$e['id']);
		
		$datos = new Datos();
		
		$datos->conectar();
		
		$query = "DELETE FROM " . $this->tabla;
				
		$query2 = '';
		
		if(!empty($where)){
			
			foreach($where as $k=>$v){
			
				$query2 .= $k  . "='" . $v . "' AND";
						
			}
			$query2 .= " WHERE " . substr($query2, 0, strlen($query2)-3);
		}
		
		$query .= $query2;
		
		$data = mysql_db_query($datos->database, $query);
				
		$datos->desconectar();		
		
	}
				
	function cloud(){
		
		$datos3 = new Datos();
		
		$datos3->conectar();
		
		$es = $this->index(null, $datos3);
		
		$datos3->desconectar();
		
		return $es;
	}
}

?>